<template>
  <div class="page-container">
    <h1 class="page-title">👣 足迹</h1>
    
    <!-- 统计卡片 -->
    <div class="card stats-card" v-if="stats">
      <div class="stat-item">
        <div class="stat-value">{{ stats.totalSessions }}</div>
        <div class="stat-label">散步次数</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ formatDistance(stats.totalDistance) }}</div>
        <div class="stat-label">总距离</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ stats.totalPOIs }}</div>
        <div class="stat-label">访问景点</div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading" v-if="loading">
      <div class="loading-spinner"></div>
    </div>
    
    <!-- 空状态 -->
    <div class="empty-state" v-else-if="sessions.length === 0">
      <img src="/images/footprint.png" alt="无足迹">
      <p>还没有散步记录</p>
      <p style="font-size: 14px;">开始你的第一次散步吧！</p>
      <button class="btn btn-primary" @click="$router.push('/route-planner')" style="margin-top: 16px;">
        开始散步
      </button>
    </div>
    
    <!-- 散步记录列表 -->
    <div class="session-list" v-else>
      <div 
        class="session-item" 
        v-for="session in sessions" 
        :key="session.id"
        @click="viewSession(session)"
      >
        <div class="session-header">
          <span class="session-date">{{ formatDate(session.start_time) }}</span>
          <span class="session-status" :class="session.status">
            {{ getStatusText(session.status) }}
          </span>
        </div>
        <div class="session-stats">
          <div class="stat-item">
            <div class="stat-value">{{ formatDistance(session.total_distance) }}</div>
            <div class="stat-label">距离</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ formatDuration(session.duration) }}</div>
            <div class="stat-label">时长</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ session.visited_pois?.length || 0 }}</div>
            <div class="stat-label">景点</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 详情弹窗 -->
    <div class="modal-overlay" v-if="selectedSession" @click.self="selectedSession = null">
      <div class="modal-content">
        <h3>散步详情</h3>
        <div id="detail-map" class="map-container"></div>
        <div class="session-detail">
          <p><strong>日期:</strong> {{ formatDate(selectedSession.start_time) }}</p>
          <p><strong>距离:</strong> {{ formatDistance(selectedSession.total_distance) }}</p>
          <p><strong>时长:</strong> {{ formatDuration(selectedSession.duration) }}</p>
          <p v-if="selectedSession.visited_pois?.length">
            <strong>访问景点:</strong> {{ selectedSession.visited_pois.map(p => p.name).join(', ') }}
          </p>
        </div>
        <button class="btn btn-secondary" @click="selectedSession = null">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import { sessionApi } from '../utils/api'
import { formatDistance } from '../utils/location'

export default {
  name: 'Footprint',
  data() {
    return {
      loading: false,
      sessions: [],
      stats: null,
      selectedSession: null,
      detailMap: null
    }
  },
  mounted() {
    this.loadSessions()
  },
  watch: {
    selectedSession(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.initDetailMap()
        })
      }
    }
  },
  methods: {
    formatDistance,
    
    async loadSessions() {
      this.loading = true
      
      try {
        const response = await sessionApi.getHistory()
        this.sessions = response.data || response.sessions || []
        this.calculateStats()
      } catch (error) {
        console.error('加载散步记录失败:', error)
        this.sessions = []
      } finally {
        this.loading = false
      }
    },
    
    calculateStats() {
      this.stats = {
        totalSessions: this.sessions.length,
        totalDistance: this.sessions.reduce((sum, s) => sum + (s.total_distance || 0), 0),
        totalPOIs: this.sessions.reduce((sum, s) => sum + (s.visited_pois?.length || 0), 0)
      }
    },
    
    viewSession(session) {
      this.selectedSession = session
    },
    
    initDetailMap() {
      if (!this.selectedSession?.route_history) return
      
      // 清理旧地图
      if (this.detailMap) {
        this.detailMap.remove()
      }
      
      const waypoints = this.selectedSession.route_history
      if (waypoints.length === 0) return
      
      const center = waypoints[Math.floor(waypoints.length / 2)]
      this.detailMap = L.map('detail-map').setView([center.latitude, center.longitude], 14)
      
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap'
      }).addTo(this.detailMap)
      
      // 绘制路径
      const points = waypoints.map(wp => [wp.latitude, wp.longitude])
      L.polyline(points, { color: '#4CAF50', weight: 4 }).addTo(this.detailMap)
      
      // 起点标记
      L.marker(points[0]).addTo(this.detailMap).bindPopup('起点')
      
      // 终点标记
      L.marker(points[points.length - 1]).addTo(this.detailMap).bindPopup('终点')
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    
    formatDuration(seconds) {
      if (!seconds) return '0分钟'
      const hours = Math.floor(seconds / 3600)
      const mins = Math.floor((seconds % 3600) / 60)
      if (hours > 0) {
        return `${hours}小时${mins}分钟`
      }
      return `${mins}分钟`
    },
    
    getStatusText(status) {
      const texts = {
        'completed': '已完成',
        'active': '进行中',
        'paused': '已暂停'
      }
      return texts[status] || status
    }
  }
}
</script>

<style scoped>
.stats-card {
  display: flex;
  justify-content: space-around;
  padding: 24px 16px;
}

.stats-card .stat-item {
  text-align: center;
}

.stats-card .stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #4CAF50;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background: #fff;
  border-radius: 16px;
  padding: 24px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-content h3 {
  margin-bottom: 16px;
}

.session-detail {
  margin: 16px 0;
}

.session-detail p {
  margin-bottom: 8px;
}
</style>
